package com.haifeng.jupiter.gateway.exception;

import cn.hutool.http.HttpStatus;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.haifeng.jupiter.gateway.base.Rest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * <p>
 *  网关异常通用处理器，只作用在webflux 环境下
 * </p>
 *
 * @author: Haifeng
 * @date: 2020-09-16
 */
@Slf4j
@Order(-1)
@Configuration
@RequiredArgsConstructor
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {

	private final ObjectMapper objectMapper;

	@Override
	public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
		ServerHttpResponse response = exchange.getResponse();
		if (response.isCommitted()) {
			return Mono.error(ex);
		}
		response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
		return response.writeWith(Mono.fromSupplier(() -> {
			DataBufferFactory bufferFactory = response.bufferFactory();
			try {
				Rest error = Rest.error(ex.getMessage());
				// ResponseStatus异常
				if (ex instanceof ResponseStatusException) {
					ResponseStatusException statusException = (ResponseStatusException) ex;
					int code = statusException.getStatus().value();
					error = Rest.error(code, statusException.getMessage());
					if (code == HttpStatus.HTTP_UNAVAILABLE){
						error = Rest.error(code, statusException.getReason().replace("Unable to find instance for ","")+"服务不可用");
					}
					int fnn = 499;
					int szz = 600;
					if (fnn < code && code < szz && code != HttpStatus.HTTP_UNAVAILABLE){
						// 5xx不包含503则打出error日志
						log.error("网关全局异常:{}", statusException);
					}else {
						// 其他则打出warn日志
						log.warn("网关全局异常:{}", statusException);
					}
				}else if (ex instanceof BusinessException){
					BusinessException businessException = (BusinessException)ex;
					error = Rest.error(businessException.getCode(), businessException.getMessage());
					log.warn("网关业务异常:{}", error);
				}
				return bufferFactory.wrap(objectMapper.writeValueAsBytes(error));
			}catch (JsonProcessingException e) {
				log.warn("Error writing response", ex);
				return bufferFactory.wrap(new byte[0]);
			}
		}));
	}
}
